package com.example.back.controller;

import com.example.common.support.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.example.back.jpa.*;
import com.example.back.utils.TradeNumUtils;
import com.example.common.cqsupervision.dto.req.*;
import com.example.common.cqsupervision.dto.req.MedicalStaff.Qualification;
import com.example.common.cqsupervision.dto.req.Registration.Recipe;
import com.example.common.cqsupervision.utils.HttpHelp;
import com.example.common.cqsupervision.utils.Sgin;
import com.example.common.entity.*;

@RestController
@Api(tags = "重庆卫健委")
@RequestMapping("/CqJg")
public class CqJgController {
    @Resource
    private TradeNumUtils tradeNumUtils;
    @Resource
    private HospitalRepository hospitalRepository;
    @Resource
    private SupervisionConfigRepository supervisionConfigRepository;
    @Resource
    private SupervisionLogRepository supervisionLogRepository;
    @Resource
    private OrderMainRepository orderMainRepository;
    @Resource
    private DoctorBaseInfoRepository doctorBaseInfoRepository;
    @Resource
    private DepartmentRository departmentRository;
    @Resource
    private ClientPatientsInfoRepository clientPatientsInfoRepository;
    @Resource
    private RxMainRepository rxMainRepository;
    @Resource
    private PatientsInfoRepository patientsInfoRepository;
    @Resource
    private PharmacistRepository pharmacistRepository;
    @Resource
    private LogisticsDRepository logisticsDRepository;
    @Resource
    private RxDrugsRepository rxDrugsRepository;

    //#region 基础业务
    @ApiOperation(value = "医疗机构维护 Q305")
    @PostMapping(value = "/HospitalInfo")
    public Result<Object> HospitalInfo(HttpServletRequest request) {
        Hospital hospital = hospitalRepository.findByLast();

        ReqBody<HospitalInfo> body = new ReqBody<>();

        List<HospitalInfo> hList = new ArrayList<>();
        HospitalInfo h = new HospitalInfo();
        h.setHospitalName(hospital.getOrgName());
        h.setYljgdm(hospital.getOrgCode());
        h.setHospitalCertiCode("hospitalCertiCode");
        h.setLevel("三级甲");
        h.setChangeType("1");
                
        List<HospitalInfo.Qualification> lsit = new ArrayList<>();
        HospitalInfo.Qualification q = new HospitalInfo.Qualification();
        q.setAvailableMark("1");
        q.setBeginDate("20200201000000");
        lsit.add(q);        
        h.setQualificationList(lsit);
        hList.add(h);
        body.setBody(hList);        
        
        doSend(request, body, "Q305", "");

        return Result.success();
    }

    @ApiOperation(value = "医疗目录上传 Q320")
    @PostMapping(value = "/MedicalDirectory")
    public Result<Object> MedicalDirectory(HttpServletRequest request) {

        ReqBody<MedicalDirectory> body = new ReqBody<>();        

        List<MedicalDirectory> list = new ArrayList<>();
        MedicalDirectory obj = new MedicalDirectory();
        obj.setMedicalCareCode("medicalCareCode");
        obj.setMedicalCareName("medicalCareName");
        obj.setListCat("listCat");
        obj.setChargeLevel("chargeLevel");
        obj.setMedicalItemCat("medicalItemCat");
        obj.setCentreCode("centreCode");
        obj.setCentreName("centreName");
        obj.setBeginDate("beginDate");        
        
        list.add(obj);
        body.setBody(list);

        doSend(request, body,"Q320", "");
        
        return Result.success();
    }

    @ApiOperation(value = "医务人员维护 (Q370)")
    @PostMapping(value = "/MedicalStaff")
    public Result<Object> MedicalStaff(HttpServletRequest request) {

        long dcid = 123123123L;
        DoctorBaseInfo doctor = doctorBaseInfoRepository.findById(dcid).orElse(null);

        ReqBody<MedicalStaff> body = new ReqBody<>();        

        List<MedicalStaff> list = new ArrayList<>();
        MedicalStaff obj = new MedicalStaff();
        obj.setChangeType("1");       
        obj.setDoctorCode(doctor.getDcId().toString()); // 系统中医生ID dc_id
        obj.setDoctorName(doctor.getName());
        obj.setIDCard("IDCard");
        obj.setPracticingPhysician("practicingPhysician");
        obj.setHoapitalName("hoapitalName");
        obj.setDoctorRecipeQualif("doctorRecipeQualif");
        obj.setDrugAuthority("drugAuthority");
        obj.setInsuranceNo("insuranceNo");
        obj.setInsuranceUnit("insuranceUnit");
        obj.setInsuranceTime("insuranceTime");
        obj.setPhysicianCategory("physicianCategory");
        obj.setServiceState("1");
        obj.setTechnicalPosition("technicalPosition");
        List<Qualification> qualificationList = new ArrayList<>();
        Qualification q = new Qualification();
        q.setAvailableMark("1");
        q.setBeginDate("beginDate");
        qualificationList.add(q);
        obj.setQualificationList(qualificationList);
        
        list.add(obj);
        body.setBody(list);

        doSend(request, body,"Q370", "");
        
        return Result.success();
    }

    @ApiOperation(value = "科室信息上传（Q380）")
    @PostMapping(value = "/DepartmentInfo")
    public Result<Object> DepartmentInfo(HttpServletRequest request) {
        long depID = 123123L;
        HospitalDepartment department = departmentRository.findById(depID).orElse(null);

        ReqBody<DepartmentInfo> body = new ReqBody<>();

        List<DepartmentInfo> list = new ArrayList<>();
        DepartmentInfo obj = new DepartmentInfo();
        obj.setChangeType("1");
        obj.setTreatDeptCode("treatDeptCode");
        obj.setTreatDeptName("treatDeptName");
        obj.setOrgDeptCode(department.getId().toString());
        obj.setOrgDeptName(department.getName());
        obj.setServeSubject("serveSubject");
        
        list.add(obj);
        body.setBody(list);

        doSend(request, body,"Q380", "");
        
        return Result.success();
    }
    //#endregion

    //#region 挂号
    @ApiOperation(value = "在线挂号(Q299)")
    @PostMapping(value = "/Registration")
    public Result<Object> Registration(HttpServletRequest request) {
        Date now = new Date();      
        String orderno = "MP530735906038400";
        OrderMain order = orderMainRepository.findById(orderno).orElse(null);
        DoctorBaseInfo doctor = doctorBaseInfoRepository.findById(order.getDcId()).orElse(null);
        HospitalDepartment department = departmentRository.findById(doctor.getDepartId()).orElse(null);
        ClientPatientsInfo patient =  clientPatientsInfoRepository.findById(order.getPid()).orElse(null);

        ReqBody<Registration> body = new ReqBody<>();        

        List<Registration> list = new ArrayList<>();
        Registration obj = new Registration();
        obj.setMedicalNum(orderno);
        obj.setBillNum(order.getTransactionID());
        obj.setMedicalType("medicalType");
        SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMddHHmmss");
        obj.setTreatDate(sdf.format(order.getOrderPayTime()));
        obj.setDeptNum(department.getDeptOrgCode());
        obj.setDeptName(department.getDeptOrgName());
        obj.setOutpatientNumber(orderno); // ? 医院 HIS 系统中用来标识一次门诊 默认：使用系统中的问诊订单号
        obj.setSpecialpatientID("0"); // ? 特病标示 默认 0: 常规患者
        obj.setReservationType("2"); // ? 预约来源类型 默认 2:网上
        obj.setSiType("2"); // ? 医保类型 默认 2，城乡居民
        obj.setCredentialType("credentialType"); // 证件类型  默认 身份证
        obj.setCredentialNum(patient.getIdNo());
        obj.setName(patient.getName());
        obj.setGender(patient.getSex().equals("男") ? "1" : patient.getSex().equals("女") ? "2" : "9");
        sdf =new SimpleDateFormat("yyyyMMdd");
        obj.setBirthday(sdf.format(patient.getBirthday()));
        obj.setRace("Race");
        obj.setSumMoney(order.getAskMoney().toString());
        obj.setUpdateBy("updateBy");
        sdf =new SimpleDateFormat("yyyyMMddHHmmss");
        obj.setSettleDate(sdf.format(now));
        obj.setInvoiceNO("invoiceNO"); // 发票号  票据上的发票号码 ? 没有这个东西
        obj.setIsKnowAgreePaper("1");

        List<Recipe> recipeList = new ArrayList<>();
        Recipe recipe = new Recipe();
        recipe.setListCat("listCat");
        recipe.setMedicalItemCat("27"); // 挂号-27
        recipe.setRecipeNum(order.getTransactionID()); //  目录类别为 1，则上传处方号； 其余上传发票号；若没有发票号，则传收费流水号  默认支付流水号
        recipe.setRecipeSerialNum(order.getTransactionID());
        recipe.setEpitaxy("1");
        recipe.setKeepUseFlag("1");
        recipe.setRecipeDate(sdf.format(order.getPayType()));
        recipe.setHospitalChargeCode("hospitalChargeCode");
        recipe.setHospitalChargeName("hospitalChargeName");
        recipe.setPriceitemCode("priceitemCode");
        recipe.setCentreChargeCode("centreChargeCode");
        recipe.setMedicareFeeitemName("medicareFeeitemName");
        recipe.setPrice(order.getAskMoney().toString());
        recipe.setQuantity("1");
        recipe.setMoney(order.getAskMoney().toString());
        recipe.setDrugUsingAim("4");
        recipe.setDeptNum(department.getDeptOrgCode());
        recipe.setDeptName(department.getDeptOrgName());
        recipe.setSelfPayRatio("100%");

        recipeList.add(recipe);
        obj.setRecipeList(recipeList);
        
        list.add(obj);
        body.setBody(list);

        doSend(request, body,"Q299", "");
        
        return Result.success();
    }

    
    @ApiOperation(value = "互联网诊疗结算（Q300）挂号")
    @PostMapping(value = "/MedicalSettlement")
    public Result<Object> MedicalSettlement(HttpServletRequest request) {
        Date now = new Date();      
        String orderno = "MP530735906038400";
        OrderMain order = orderMainRepository.findById(orderno).orElse(null);
        DoctorBaseInfo doctor = doctorBaseInfoRepository.findById(order.getDcId()).orElse(null);
        HospitalDepartment department = departmentRository.findById(doctor.getDepartId()).orElse(null);
        ClientPatientsInfo patient =  clientPatientsInfoRepository.findById(order.getPid()).orElse(null);

        ReqBody<MedicalSettlement> body = new ReqBody<>();        

        List<MedicalSettlement> list = new ArrayList<>();
        MedicalSettlement obj = new MedicalSettlement();
        obj.setMedicalNum(orderno);
        obj.setBillNum(order.getTransactionID());
        obj.setMedicalType("medicalType");
        SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMddHHmmss");
        obj.setTreatDate(sdf.format(order.getOrderPayTime()));
        obj.setDeptNum(department.getDeptOrgCode());
        obj.setDeptName(department.getDeptOrgName());
        obj.setSpecialpatientID("0");
        obj.setReservationType("2");
        obj.setSiType("2");
        obj.setDoctorCode(doctor.getDcId().toString());
        obj.setDoctorName(doctor.getName());
        obj.setName(patient.getName());
        obj.setGender(patient.getSex().equals("男") ? "1" : patient.getSex().equals("女") ? "2" : "9");
        sdf =new SimpleDateFormat("yyyyMMdd");
        obj.setBirthday(sdf.format(patient.getBirthday()));
        obj.setRace("Race");
        obj.setSumMoney(order.getAskMoney().floatValue());
        obj.setUpdateBy("updateBy");
        sdf =new SimpleDateFormat("yyyyMMddHHmmss");
        obj.setSettleDate(sdf.format(order.getOrderPayTime()));
        obj.setInvoiceNO("invoiceNO");
        obj.setIsRegister("1");

        Number recipeSerialNum = now.getTime();
        List<MedicalSettlement.Recipe> recipeList = new ArrayList<>();
        MedicalSettlement.Recipe recipe = new MedicalSettlement.Recipe();
        recipe.setListCat("listCat");
        recipe.setMedicalItemCat("medicalItemCat");
        recipe.setRecipeNum(order.getTransactionID());
        recipe.setRecipeSerialNum(recipeSerialNum);
        recipe.setRecipeDate(sdf.format(order.getPayType()));
        recipe.setHospitalChargeCode("hospitalChargeCode");
        recipe.setHospitalChargeName("hospitalChargeName");
        recipe.setPriceitemCode("priceitemCode");
        recipe.setCentreChargeCode("centreChargeCode");
        recipe.setMedicareFeeitemName("medicareFeeitemName");
        recipe.setPrice(order.getAskMoney().floatValue());
        recipe.setQuantity(1);
        recipe.setMoney(order.getAskMoney().floatValue());
        recipe.setDeptNum(department.getDeptOrgCode());
        recipe.setDeptName(department.getDeptOrgName());
        recipe.setDoctorCode(doctor.getDcId().toString());
        recipe.setDoctorName(doctor.getName());
        recipe.setSelfPayRatio("100%");
        recipe.setKeepUseFlag("1");   

        recipeList.add(recipe);
        obj.setRecipeList(recipeList);
        
        list.add(obj);
        body.setBody(list);

        doSend(request, body,"Q300", "");
        
        return Result.success();
    }
    //#endregion

    //#region 临床业务 
    @ApiOperation(value = "线上问诊病历 (Q341)")
    @PostMapping(value = "/MedicalRecord")
    public Result<Object> MedicalRecord(HttpServletRequest request) {
        Date now = new Date();      
        String rxorderno = "RZ547352671371800";
        RxMain rxorder = rxMainRepository.findById(rxorderno).orElse(null);
        OrderMain order = orderMainRepository.findById(rxorder.getOrderNO()).orElse(null);
        PatientsInfo orderpatients = patientsInfoRepository.findById(order.getPatientsInfoID()).orElse(null);
        DoctorBaseInfo doctor = doctorBaseInfoRepository.findById(order.getDcId()).orElse(null);
        HospitalDepartment department = departmentRository.findById(doctor.getDepartId()).orElse(null);
        ClientPatientsInfo patient =  clientPatientsInfoRepository.findById(order.getPid()).orElse(null);
        Hospital hospital = hospitalRepository.findByLast();

        ReqBody<MedicalRecord> body = new ReqBody<>();

        List<MedicalRecord> list = new ArrayList<>();
        MedicalRecord obj = new MedicalRecord();
        obj.setYljgdm(hospital.getOrgCode());
        obj.setUserName(hospital.getOrgName());
        obj.setCredentialType("credentialType");
        obj.setCredentialNum(patient.getIdNo());
        obj.setMedicalNum(order.getOrderNo());
        obj.setDoctorCode(doctor.getDcId().toString());
        obj.setDoctorName(doctor.getName());
        obj.setFzbz("1");
        SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMddHHmmss");
        obj.setInquirydate(sdf.format(order.getReceiveTime()));
        obj.setDeptNum(department.getDeptOrgCode());
        obj.setDeptName(department.getDeptOrgName());
        obj.setZsjl(orderpatients.getChiefComplaint());
        obj.setZyzzmc("zyzzmc"); // ? 主要症状 没有录入地方
        obj.setZxyzdbz(rxorder.getDType() == 3 ? "1" : rxorder.getDType().toString());
        
        List<MedicalRecord.AdditionalDiagnosis> additionalDiagnosisList = new ArrayList<>();
        MedicalRecord.AdditionalDiagnosis additionalDiagnosis = new MedicalRecord.AdditionalDiagnosis();
        additionalDiagnosis.setDiagnosisCode(rxorder.getDisCode());
        additionalDiagnosis.setDiagnosisName(rxorder.getDialectical());
        additionalDiagnosis.setDiagnosisClassify("2");
        additionalDiagnosis.setDiagnosisType("diagnosisType"); 
        additionalDiagnosisList.add(additionalDiagnosis);
        if(rxorder.getDType() == 1 || rxorder.getDType() == 3){
            obj.setZyszms(rxorder.getZyszms());
            obj.setSfscsx("1");
            obj.setBzfx(rxorder.getBzfx());
            obj.setZxdm(rxorder.getZDialecticsCode());
            obj.setZxmc(rxorder.getZDialectics());
            additionalDiagnosis = new MedicalRecord.AdditionalDiagnosis();
            additionalDiagnosis.setDiagnosisCode(rxorder.getZDisCode());
            additionalDiagnosis.setDiagnosisName(rxorder.getZDialectical());
            additionalDiagnosis.setDiagnosisClassify("1");
            additionalDiagnosis.setDiagnosisType("diagnosisType"); 
            additionalDiagnosisList.add(additionalDiagnosis);
        }
        obj.setAdditionalDiagnosisList(additionalDiagnosisList);
        obj.setJzzdsm(rxorder.getJzzdsm());
        obj.setSfxylygc(rxorder.getSfxylygc() ? "1" : "0" );
        obj.setReferral("referral");
        obj.setJdrq("jdrq");
        obj.setTbrq(sdf.format(now));
        
        list.add(obj);
        body.setBody(list);

        doSend(request, body,"Q341", "");
        
        return Result.success();
    }

    @ApiOperation(value = "线上处方点评(Q310)")
    @PostMapping(value = "/Prescription")
    public Result<Object> Prescription(HttpServletRequest request) {
        Date now = new Date();      
        String rxorderno = "RZ547352671371800";
        RxMain rxorder = rxMainRepository.findById(rxorderno).orElse(null);
        List<RxDrugs> rxDrugsList = rxDrugsRepository.findByRxOrderNO(rxorderno);
        OrderMain order = orderMainRepository.findById(rxorder.getOrderNO()).orElse(null);
        LogisticsD logisticsD = logisticsDRepository.findById(rxorderno).orElse(null);
        DoctorBaseInfo doctor = doctorBaseInfoRepository.findById(order.getDcId()).orElse(null);
        HospitalDepartment department = departmentRository.findById(doctor.getDepartId()).orElse(null);
        Pharmacist pharmacist = pharmacistRepository.findById(rxorder.getChkDcId()).orElse(null);
        ClientPatientsInfo patient =  clientPatientsInfoRepository.findById(order.getPid()).orElse(null);

        ReqBody<Prescription> body = new ReqBody<>();

        List<Prescription> list = new ArrayList<>();
        Prescription obj = new Prescription();
        obj.setPatientNo(patient.getPid().toString());
        obj.setMedicalNum(rxorder.getOrderNO());
        obj.setPatientName(patient.getName());
        obj.setPatientSex(patient.getSex().equals("男") ? "1" : patient.getSex().equals("女") ? "2" : "9");
        obj.setCredentialType("credentialType");
        obj.setCredentialNum(patient.getIdNo());
        SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMdd");
        obj.setBirthday(sdf.format(patient.getBirthday()));
        obj.setRace("race");
        obj.setRecipeNum(rxorderno);
        obj.setRecipeStatus("0"); // 处方状态  0.正常处方
        obj.setRecipeType("1"); // 处方类别  默认 1.普通处方
        obj.setRecipeCategory(rxorder.getDType() == 1 ? "1" : rxorder.getDType() == 2 ? "3" : rxorder.getDType() == 3 ? "2" : "");
        obj.setDeptCode(department.getDeptOrgCode());
        obj.setDeptName(department.getDeptOrgName());
        obj.setHosDeptCode(department.getId().toString());
        obj.setHosDeptName(department.getName());
        obj.setRecipeDocCode(doctor.getDcId().toString());
        obj.setRecipeDocName(doctor.getName());
        obj.setRecipeDocTitle("recipeDocTitle");
        // ca签名
        obj.setRecipeDocSignatureValue(rxorder.getRecipeDocSignatureValue());
        obj.setRecipeDocSigncertificate(rxorder.getRecipeDocSigncertificate());
        obj.setRecipeDocSignatureXML(rxorder.getRecipeDocSignatureXml());
        obj.setRecipeDocTimeStamp(rxorder.getRecipeDocTimeStamp());

        sdf =new SimpleDateFormat("yyyyMMddHHmmss");
        obj.setRecipeDate(sdf.format(rxorder.getCreateTime()));
        obj.setTrialPharmCode(pharmacist.getDcId().toString());
        obj.setTrialPharmName(pharmacist.getName());
        obj.setTrialPharmTitle("trialPharmTitle");
        // ca
        obj.setTrialPharmSignatureValue(rxorder.getTrialPharmSignatureValue());
        obj.setTrialPharmSigncertificate(rxorder.getTrialPharmSigncertificate());
        obj.setTrialPharmSignatureXML(rxorder.getTrialPharmSignatureXml());
        obj.setTrialPharmTimeStamp(rxorder.getTrialPharmTimeStamp());

        sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        obj.setTrialDate(sdf.format(rxorder.getChkTime()));
        obj.setRecipeFeeTotal(rxorder.getSalePrice().subtract(rxorder.getFreight()).toString());
        obj.setRecipedistribut(logisticsD.getLType() == 0 ? "1" : logisticsD.getLType() == 1 ? "2" : "");
        obj.setKeepUseFlag("1");

        List<Prescription.AdditionalDiagnosis> additionalDiagnosisList = new ArrayList<>();
        Prescription.AdditionalDiagnosis additionalDiagnosis = new Prescription.AdditionalDiagnosis();
        additionalDiagnosis.setDiagnosisCode(rxorder.getDisCode());
        additionalDiagnosis.setDiagnosisName(rxorder.getDialectical());
        additionalDiagnosis.setDiagnosisClassify("2");
        additionalDiagnosis.setDiagnosisType("diagnosisType"); 
        additionalDiagnosis.setDiagSort("0");
        additionalDiagnosisList.add(additionalDiagnosis);
        if(rxorder.getDType() == 1 || rxorder.getDType() == 3){
            obj.setSymptomCode(rxorder.getZDialecticsCode());
            obj.setSymptomCodeName(rxorder.getZDialectics());
            additionalDiagnosis = new Prescription.AdditionalDiagnosis();
            additionalDiagnosis.setDiagnosisCode(rxorder.getZDisCode());
            additionalDiagnosis.setDiagnosisName(rxorder.getZDialectical());
            additionalDiagnosis.setDiagnosisClassify("1");
            additionalDiagnosis.setDiagnosisType("diagnosisType"); 
            additionalDiagnosis.setDiagSort("0");
            additionalDiagnosisList.add(additionalDiagnosis);
        }
        additionalDiagnosisList.add(additionalDiagnosis);
        obj.setAdditionalDiagnosisList(additionalDiagnosisList);

        List<Prescription.Allergen> allergenList = new ArrayList<>(); // ？ 过敏信息 过敏信息编码 过敏物  过敏反应
        Prescription.Allergen allergen = new Prescription.Allergen();
        allergenList.add(allergen);
        obj.setAllergenList(allergenList);

        Number recipeSerialNum = now.getTime();
        List<Prescription.Drug> drugList = new ArrayList<>();
        for (RxDrugs rxdrug : rxDrugsList) {
            Prescription.Drug drug = new Prescription.Drug();
            drug.setRecipeSerialNum(recipeSerialNum.toString());
            drug.setGroupNo("groupNo");
            drug.setHospitalDrugCode(rxdrug.getDrugId().toString());
            drug.setDrugCommonName(rxdrug.getDrugName());
            drug.setDrugDose(rxdrug.getDoes().toString());
            drug.setDrugDoseUnit(rxdrug.getDoesUnit());
            drug.setMedicationRoute("medicationRoute");
            drug.setFrequency("frequency");
            drug.setFormulation("formulation");
            drug.setDeliverNum("deliverNum");
            drug.setDeliverNumUnit("deliverNumUnit");
            drug.setMoney(rxdrug.getPrice().multiply(BigDecimal.valueOf(rxdrug.getNum())).toString());
            drug.setDrugCategory(rxdrug.getType() == 1 ? "3" : rxdrug.getType() == 2 ? "1" : rxdrug.getType() == 3 ? "2" : "");
            drugList.add(drug);            
        }
        obj.setDrugList(drugList);        

        list.add(obj);
        body.setBody(list);

        doSend(request, body,"Q310", "");
        
        return Result.success();
    }

    @ApiOperation(value = "互联网诊疗结算（Q300）处方")
    @PostMapping(value = "/MedicalSettlementcf")
    public Result<Object> MedicalSettlementcf(HttpServletRequest request) {
        Date now = new Date();      
        String rxorderno = "RZ547352671371800";
        RxMain rxorder = rxMainRepository.findById(rxorderno).orElse(null);
        List<RxDrugs> rxDrugsList = rxDrugsRepository.findByRxOrderNO(rxorderno);
        OrderMain order = orderMainRepository.findById(rxorder.getOrderNO()).orElse(null);
        LogisticsD logisticsD = logisticsDRepository.findById(rxorderno).orElse(null);
        DoctorBaseInfo doctor = doctorBaseInfoRepository.findById(order.getDcId()).orElse(null);
        HospitalDepartment department = departmentRository.findById(doctor.getDepartId()).orElse(null);
        ClientPatientsInfo patient =  clientPatientsInfoRepository.findById(order.getPid()).orElse(null);

        ReqBody<MedicalSettlement> body = new ReqBody<>();        

        List<MedicalSettlement> list = new ArrayList<>();
        MedicalSettlement obj = new MedicalSettlement();
        obj.setMedicalNum(order.getOrderNo());
        obj.setBillNum(order.getTransactionID());
        obj.setMedicalType("medicalType");
        SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMddHHmmss");
        obj.setTreatDate(sdf.format(order.getOrderPayTime()));
        obj.setDeptNum(department.getDeptOrgCode());
        obj.setDeptName(department.getDeptOrgName());
        obj.setSpecialpatientID("0");
        obj.setReservationType("2");
        obj.setSiType("2");
        obj.setDoctorCode(doctor.getDcId().toString());
        obj.setDoctorName(doctor.getName());
        obj.setName(patient.getName());
        obj.setGender(patient.getSex().equals("男") ? "1" : patient.getSex().equals("女") ? "2" : "9");
        sdf =new SimpleDateFormat("yyyyMMdd");
        obj.setBirthday(sdf.format(patient.getBirthday()));
        obj.setRace("Race");
        obj.setSumMoney(rxorder.getSalePrice().subtract(rxorder.getFreight()).floatValue());
        obj.setUpdateBy("updateBy");
        sdf =new SimpleDateFormat("yyyyMMddHHmmss");
        obj.setSettleDate(sdf.format(rxorder.getOrderPayTime()));
        obj.setInvoiceNO("invoiceNO");
        obj.setIsRegister("0");
        
        List<MedicalSettlement.AdditionalDiagnosis> additionalDiagnosisList = new ArrayList<>();
        MedicalSettlement.AdditionalDiagnosis additionalDiagnosis = new MedicalSettlement.AdditionalDiagnosis();
        additionalDiagnosis.setDiagnosisCode(rxorder.getDisCode());
        additionalDiagnosis.setDiagnosisName(rxorder.getDialectical());
        additionalDiagnosis.setDiagnosisClassify("2");
        additionalDiagnosis.setDiagnosisType("diagnosisType"); 
        additionalDiagnosis.setDiagSort("0");
        additionalDiagnosisList.add(additionalDiagnosis);
        if(rxorder.getDType() == 1 || rxorder.getDType() == 3){
            obj.setSymptomCode(rxorder.getZDialecticsCode());
            obj.setSymptomCodeName(rxorder.getZDialectics());
            additionalDiagnosis = new MedicalSettlement.AdditionalDiagnosis();
            additionalDiagnosis.setDiagnosisCode(rxorder.getZDisCode());
            additionalDiagnosis.setDiagnosisName(rxorder.getZDialectical());
            additionalDiagnosis.setDiagnosisClassify("1");
            additionalDiagnosis.setDiagnosisType("diagnosisType"); 
            additionalDiagnosis.setDiagSort("0");
            additionalDiagnosisList.add(additionalDiagnosis);
        }
        additionalDiagnosisList.add(additionalDiagnosis);
        obj.setAdditionalDiagnosisList(additionalDiagnosisList);
        

        Number recipeSerialNum = now.getTime();
        List<MedicalSettlement.Recipe> recipeList = new ArrayList<>();
        for (RxDrugs rxDrugs : rxDrugsList) {
            MedicalSettlement.Recipe recipe = new MedicalSettlement.Recipe();
            recipe.setListCat("listCat");
            recipe.setMedicalItemCat("medicalItemCat");
            recipe.setRecipeNum(rxorder.getRxOrderNO());
            recipe.setRecipeSerialNum(recipeSerialNum);
            recipe.setRecipeDate(sdf.format(rxorder.getCreateTime()));
            recipe.setProductName(rxDrugs.getDrugName());
            recipe.setHospitalChargeCode("hospitalChargeCode");
            recipe.setHospitalChargeName("hospitalChargeName");
            recipe.setPriceitemCode("priceitemCode");
            recipe.setCentreChargeCode("centreChargeCode");
            recipe.setMedicareFeeitemName("medicareFeeitemName");
            recipe.setPrice(rxDrugs.getPrice().floatValue());
            recipe.setQuantity(rxDrugs.getNum().floatValue());
            recipe.setMoney(rxDrugs.getPrice().multiply(BigDecimal.valueOf(rxDrugs.getNum())).floatValue());
            recipe.setDeptNum(department.getDeptOrgCode());
            recipe.setDeptName(department.getDeptOrgName());
            recipe.setDoctorCode(doctor.getDcId().toString());
            recipe.setDoctorName(doctor.getName());
            recipe.setSelfPayRatio("100%");
            recipe.setKeepUseFlag("1");
            recipe.setRecipedistribut(logisticsD.getLType() == 0 ? "1" : logisticsD.getLType() == 1 ? "2" : "");
    
            recipeList.add(recipe);            
        }
        obj.setRecipeList(recipeList);
        
        list.add(obj);
        body.setBody(list);

        doSend(request, body,"Q300", "");
        
        return Result.success();
    }
    
    //#endregion
    
    private void doSend(HttpServletRequest request, ReqBody<?> body, String busseID, String apiUrl){
        HttpHelp post = new HttpHelp();

        long hid = hospitalRepository.findByLast().getId();
        SupervisionConfig config = supervisionConfigRepository.findById(hid).orElse(null);
        
        Sgin sgin = new Sgin();
        sgin.setXRbKey(config.getKey());
        sgin.setSecret(config.getSecret());

        Head head = JSONObject.parseObject(config.getHead(), Head.class);
        head.setBusseID(busseID);
        head.setClientmacAddress(post.getMac(request));  
        body.setHead(head);

        head.setRecordCount(body.getBody().size() + "");

        AdditionInfo additionInfo = new AdditionInfo();
        body.setAdditionInfo(additionInfo);

        String hCode = config.getCode();
        SupervisionLog log = tradeNumUtils.createTradeNum(hCode);
        head.setSendTradeNum(log.getSendTradeNum());
        Map<String, Object> mbody = new HashMap<>();
        mbody.put("package", body);
        log.setRequest(JSONObject.toJSONString(mbody));

        String resp = post.doSupervisionPost(config.getUrl() + apiUrl, sgin, mbody);
        log.setResponse(resp);
        Map<?, ?> resmap = JSONObject.parseObject(log.getResponse(), Map.class);
        ReqBody<?> resbody = JSONObject.parseObject(resmap.get("package").toString(), ReqBody.class);
        log.setIsSuccess(resbody.getAdditionInfo().getErrorCode().equals("0"));

        supervisionLogRepository.save(log);
    }
    
}
